
import { ref, onBeforeMount  ,type UnwrapRef} from 'vue'
import http from "@/utils/request";
import { ElMessage, ElMessageBox } from 'element-plus'

import type { Entity } from "@/api/types";

export const num = 100;
export default function <T  extends Entity>(listUrl: string, removeUrl: string) {



    //列表的数据
    const tableData = ref<T[]>([])

    //是否显示修改页面
    const show = ref(false)


    //待修改的id
    let editId = ref<number>()

    function handleEdit(index: number, row: T) {
        editId.value= row.id as number
        show.value = true
    }


    function handleDelete(index: number, row: T) {


        ElMessageBox.confirm(
            '是否删除???',
            'Warning',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                //调用axios对象 
                const url = removeUrl + row.id

                http.get<boolean>(url).then(data => {

                    if (data) {
                        ElMessage({ message: '删除成功', type: 'success', })
                        load()
                    } else {
                        ElMessage({ message: '删除失败了', type: 'error', })
                    }

                })
                    .catch(error => { })
            })
    }


    //调用axios对象  获取列表的数据
    function load() {

        
        http.get<UnwrapRef<T[]>>(listUrl)
            .then(data => { tableData.value = data })
            .catch(error => { })
    }

    //显示 修改、添加页面
    function add() {
        show.value = true
    }

    //关闭dialog
    function clostDialog() {
        load();
        show.value = false
    }


    //查询数据
    onBeforeMount(() => {
        load();
    })




    return { tableData, show, editId, handleEdit, handleDelete, load, add, clostDialog }



}










